<%@ page import="com.example.dao.UserDao" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page pageEncoding="UTF-8"%>
<%
    request.setCharacterEncoding("UTF-8");
    
    // 获取表单参数
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    String realname = request.getParameter("realname");
    String phone = request.getParameter("phone");

    // 验证必填字段
    if (username == null || username.trim().isEmpty() ||
        password == null || password.trim().isEmpty() ||
        email == null || email.trim().isEmpty()) {
        
        response.sendRedirect("register.jsp?error=用户名、密码和邮箱都是必填的");
        return;
    }

    // 验证密码长度
    if (password.length() < 6) {
        response.sendRedirect("register.jsp?error=密码长度不能少于6位");
        return;
    }

    try {
        UserDao userDao = new UserDao();
        
        // 检查用户名是否已存在
        if (userDao.userExists(username)) {
            response.sendRedirect("register.jsp?error=用户名已存在");
            return;
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 实际项目中应该加密密码
        user.setEmail(email);
        user.setRealname(realname);
        user.setPhone(phone);

        // 保存到数据库
        userDao.createUser(user);

        // 注册成功，重定向到登录页面
        response.sendRedirect("login.jsp?registered=true");
    } catch (Exception e) {
        response.sendRedirect("register.jsp?error=注册失败: " + e.getMessage());
    }
%>